const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const _ = db.command

// 验证管理员token
async function verifyAdminToken(token) {
  try {
    const result = await db.collection('admin_tokens').where({
      token: token,
      expireTime: _.gt(new Date())
    }).get()
    
    if (result.data.length > 0) {
      // 更新token最后使用时间
      await db.collection('admin_tokens').doc(result.data[0]._id).update({
        data: {
          lastUsed: new Date()
        }
      })
      return true
    }
    return false
  } catch (error) {
    console.error('验证管理员token错误:', error)
    return false
  }
}

exports.main = async (event, context) => {
  const { action, adminToken, page = 1, limit = 20, search = '', userId, userData } = event
  
  console.log('用户管理操作:', { action, page, limit, search, userId })
  
  // 验证管理员权限
  if (!await verifyAdminToken(adminToken)) {
    return { 
      success: false, 
      message: '权限不足或登录已过期，请重新登录' 
    }
  }
  
  try {
    switch (action) {
      case 'list':
        // 获取用户列表
        let query = db.collection('users')
        
        // 搜索条件
        if (search) {
          query = query.where({
            nickName: db.regExp({
              regexp: search,
              options: 'i'
            })
          })
        }
        
        // 获取总数
        const countResult = await query.count()
        const total = countResult.total
        
        // 获取分页数据
        const users = await query
          .skip((page - 1) * limit)
          .limit(limit)
          .orderBy('createdAt', 'desc')
          .get()
        
        // 处理用户数据，映射字段名
        const processedUsers = users.data.map(user => {
          return {
            ...user,
            openid: user._openid || '',
            createTime: user.createdAt || null,
            lastLoginTime: user.lastLoginAt || null
          }
        })
        
        console.log('获取用户列表成功:', { total, count: processedUsers.length })
        
        return {
          success: true,
          data: processedUsers,
          total: total,
          page: page,
          limit: limit
        }
        
      case 'update':
        // 更新用户信息
        if (!userId || !userData) {
          return { success: false, message: '参数不完整' }
        }
        
        await db.collection('users').doc(userId).update({
          data: {
            ...userData,
            updateTime: new Date()
          }
        })
        
        console.log('用户信息更新成功:', { userId })
        return { success: true, message: '用户信息更新成功' }
        
      case 'changeStatus':
        // 修改用户状态
        if (!userId || userData.status === undefined) {
          return { success: false, message: '参数不完整' }
        }
        
        // 确保状态是数字类型
        const statusValue = Number(userData.status)
        if (statusValue !== 0 && statusValue !== 1) {
          return { success: false, message: '状态值无效' }
        }
        
        await db.collection('users').doc(userId).update({
          data: { 
            status: statusValue,
            updateTime: new Date()
          }
        })
        
        console.log('用户状态修改成功:', { userId, status: statusValue })
        return { success: true, message: '用户状态修改成功' }
        
      case 'getUserActivities':
        // 获取用户活动参与记录
        const { openId } = event
        if (!openId) {
          return { success: false, message: 'openId不能为空' }
        }
        
        console.log('开始查询用户活动记录，用户openId:', openId)
        
        const userRecord = await db.collection('user_activity_relay')
          .where({
            userId: openId
          })
          .get()
        
        console.log('查询结果:', userRecord.data)
        
        // 从activityRecords数组中提取活动数据
        let processedActivities = []
        if (userRecord.data.length > 0 && userRecord.data[0].activityRecords) {
          processedActivities = userRecord.data[0].activityRecords.map(item => ({
            activityId: item.activityId,
            status: item.status || 'registered',
            registrationTime: item.registrationTime
          }))
        }
        
        console.log('处理后的活动记录:', processedActivities)
        
        return {
          success: true,
          data: processedActivities
        }
        
      default:
        return { success: false, message: '无效的操作类型' }
    }
  } catch (error) {
    console.error('用户管理操作错误:', error)
    return { 
      success: false, 
      error: error.message,
      message: '操作失败，请稍后重试'
    }
  }
}